﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using MovieDB.Business;
using MovieDB.Data.Entities;
using MovieDB.Web.ViewModels;

namespace MovieDB.Web.Controllers
{
    public class CategoryController : Controller
    {
        private IReferenceDataManager _refDataManager;
        public CategoryController(IReferenceDataManager refDataManager)
        {
            _refDataManager = refDataManager;
        }

        public ActionResult Index()
        {
            List<Category> categories = _refDataManager.GetAllCategories();
            return View(categories);
        }

        public ActionResult Edit(int id)
        {
            Category cat = _refDataManager.GetCategoryById(id);
            var catViewModel = new CategoryViewModel();
            Mapper.Map(cat, catViewModel);
            return View(catViewModel);
        }

        [HttpPost]
        public ActionResult Edit(CategoryViewModel catViewModel)
        {
            if (ModelState.IsValid)
            {
                // Update category
                Category category = _refDataManager.GetCategoryById(catViewModel.Id);
                Mapper.Map(catViewModel, category);
                _refDataManager.SaveCategory(category);

                return RedirectToAction("Index");
            }
            else
            {
                return View(catViewModel);
            }
        }

        public ActionResult Delete(int id)
        {
            _refDataManager.DeleteCategoryById(id);

            return RedirectToAction("Index");
        }

        public ActionResult Create()
        {
            var catViewModel = new CategoryViewModel();
            return View(catViewModel);
        }

        [HttpPost]
        public ActionResult Create(CategoryViewModel catViewModel)
        {
            if (ModelState.IsValid)
            {
                // Update category
                var category = new Category();
                Mapper.Map(catViewModel, category);
                _refDataManager.SaveCategory(category);

                return RedirectToAction("Index");
            }
            else
            {
                return View(catViewModel);
            }
        }

    }
}
